package edgeEntity

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"strconv"
)

type DeviceSequenceEntity struct {
	BaseEntity *commEntity.BaseEntity // 基本信息

	DeviceName  string                 // 设备名称
	MetricName  string                 // 指标名称
	Timestamp   int64                  // 时间戳
	DeviceValue map[string]interface{} // 配置参数
}

type deviceSequencePo struct {
	Id          int64                  `json:"id" db:"id"`                    // 对象id
	CreateTime  int64                  `json:"createTime" db:"create_time"`   // 创建时间
	DeviceName  string                 `json:"deviceName" db:"device_name"`   // 设备名称
	MetricName  string                 `json:"metricName" db:"metric_name"`   // 事件名称
	Timestamp   int64                  `json:"timestamp" db:"timestamp"`      // 事件名称
	DeviceValue map[string]interface{} `json:"deviceValue" db:"device_value"` // 扩展参数
}

func (e *DeviceSequenceEntity) Type() string {
	return "DeviceSequenceEntity"
}

func (e *DeviceSequenceEntity) TableName() string {
	return "tb_sequence"
}

func (e *DeviceSequenceEntity) GetBaseEntity() *commEntity.BaseEntity {
	return e.BaseEntity
}

func (e *DeviceSequenceEntity) Instance() *DeviceSequenceEntity {
	return &DeviceSequenceEntity{
		BaseEntity:  new(commEntity.BaseEntity),
		DeviceValue: make(map[string]interface{}),
	}
}

func (e *DeviceSequenceEntity) NewEntity() commEntity.IEntity {
	return e.Instance()
}

func (e *DeviceSequenceEntity) NewPo() interface{} {
	return &deviceSequencePo{
		DeviceValue: make(map[string]interface{}),
	}
}

func (e *DeviceSequenceEntity) MakeServiceKey() string {
	p := e.MakeServiceKeyList()
	return commEntity.MakeServiceKey(p)
}

func (e *DeviceSequenceEntity) MakeServiceKeyList() []string {
	var p []string
	p = append(p, e.DeviceName)
	p = append(p, e.MetricName)
	p = append(p, strconv.FormatInt(e.Timestamp, 10))
	return p
}

func (e *DeviceSequenceEntity) BuildByJson(jsn *string) error {
	var po deviceSequencePo
	err := json.Unmarshal([]byte(*jsn), &po)
	if err != nil {
		return err
	}

	e.BuildByPo(&po)
	return nil
}

func (e *DeviceSequenceEntity) BuildToJson() (string, error) {
	po := e.BuildToPo()
	code, err := json.Marshal(po)
	if err != nil {
		return "", err
	}

	return string(code), nil
}

func (e *DeviceSequenceEntity) BuildByPo(pop interface{}) {
	ptr := e
	po := pop.(*deviceSequencePo)

	ptr.BaseEntity.Id = po.Id
	ptr.BaseEntity.CreateTime = po.CreateTime

	ptr.DeviceName = po.DeviceName
	ptr.MetricName = po.MetricName
	ptr.Timestamp = po.Timestamp
	ptr.DeviceValue = po.DeviceValue
}

func (e *DeviceSequenceEntity) BuildToPo() interface{} {
	ptr := e
	po := deviceSequencePo{}

	po.Id = ptr.BaseEntity.Id
	po.CreateTime = ptr.BaseEntity.CreateTime

	po.DeviceName = ptr.DeviceName
	po.MetricName = ptr.MetricName
	po.Timestamp = ptr.Timestamp
	po.DeviceValue = ptr.DeviceValue

	return &po
}
